package com.atguigu.gulimall.auth.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.constant.AuthServerConstant;
import com.atguigu.common.utils.HttpUtils;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.MemberRespVo;
import com.atguigu.gulimall.auth.feign.MemberFeignService;
import com.atguigu.gulimall.auth.service.OAuthService;
import com.atguigu.gulimall.auth.vo.SocialUserVo;
import com.google.common.collect.Maps;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.HashMap;

/**
 * @DESCRIPTION:
 * @author: zr
 * @DATE: 2023/1/9 23:17
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class OAuthServiceImpl implements OAuthService {
    private final MemberFeignService memberFeignService;

    @Override
    public String socialLogin(String code, HttpSession session) throws Exception {
        HashMap<String, String> headers = Maps.newHashMap();
        HashMap<String, String> queries = Maps.newHashMap();
        queries.put("client_id", "2985751559");
        queries.put("client_secret", "1c3ad057c493b71a968288757de3dd1e");
        queries.put("grant_type", "authorization_code");
        queries.put("redirect_uri", "http://auth.gulimall.com/oauth2.0/weibo/success");
        queries.put("code", code);
        HashMap<String, String> bodys = Maps.newHashMap();
        HttpResponse response = HttpUtils.doPost("https://api.weibo.com", "/oauth2/access_token", "post", headers, queries, bodys);
        if (response.getStatusLine().getStatusCode() == 200) {
            // 获取响应状态码 为200则成功
            // 获取access token
            String responseJson = EntityUtils.toString(response.getEntity());
            SocialUserVo socialUserVo = JSON.parseObject(responseJson, new TypeReference<SocialUserVo>() {
            });
            // 知道当前是哪个社交用户
            // 当前用户如果是第一次进网站 自动注册进来(为当前社交用户生成一个会员信息账号，以后这个账号就对应会员信息)
            // 调用远程服务登录或者注册用户
            R oAuthLogin = memberFeignService.oAuthLogin(socialUserVo);
            if (oAuthLogin.getCode() == 0) {
                // 远程调用成功
                MemberRespVo memberRespVo = oAuthLogin.getData("data", new TypeReference<MemberRespVo>() {
                });
                session.setAttribute(AuthServerConstant.LOGIN_USER, memberRespVo);
                log.info("社交登录成功返回对象:{}", memberRespVo.toString());
                // 登录成功
                return "redirect:http://gulimall.com";
            }
        } else {
            return "redirect:http://auth.gulimall.com/login.html";
        }
        return "redirect:http://auth.gulimall.com/login.html";
    }
}
